# -*- coding:utf-8 -*-
"""
@Time : 2022/4/24 10:11 AM
@Author: binkuolo
@Des: 常用返回类型封装
"""
from collections import namedtuple
from fastapi import HTTPException
from fastapi.responses import FileResponse
from typing import List, Any

HttpCode = namedtuple('HttpResponse', ['code', 'msg'])


class HttpResponse:
    """HTTP响应结果
    """
    SUCCESS = HttpCode(200, '成功')
    NOTSUCCESS = HttpCode(201, '业务执行失败')
    FAILED = HttpCode(0, '失败')

    BBA_REQUEST = HttpCode(400, '无法找到请求的资源')
    UNAUTHORIZED = HttpCode(401, '访问资源的权限不够')
    FORBIDDEN = HttpCode(403, '没有权限访问资源')
    NOT_FOUND = HttpCode(404, '需要访问的资源不存在')
    BAD_METHOD = HttpCode(405, '不允许的http方法')

    SYSTEM_ERROR = HttpCode(500, '系统错误')
    NOT_IMPLEMENTED = HttpCode(501, '接口未实现')
    BAD_GATEWAY = HttpCode(502, '系统错误')
    SERVICE_UAVAILABLE = HttpCode(503, '系统错误')
    GATEWAY_TIMEOUT = HttpCode(504, '请求超时')


def res_table_response(data: List = None, total: int = 0):
    """
    :param code:
    :param data:
    :param total:
    :return:
    """
    if data is None:
        data = []
    result = {
        "code": HttpResponse.SUCCESS.code,
        "rows": data,
        "total": total
    }
    return result


def base_response(code, msg, data=None, ext=None):
    """基础返回格式"""
    if data is None:
        data = []
    result = {
        "code": code,
        "msg": msg,
        "data": data
        # "time":time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    }
    if ext != None:
        for k in ext:
            result[k] = ext[k]
    return result


def file_response(path: str, name: str):
    return FileResponse(path, filename=name, media_type="application/octet-stream")


def success(msg='', data=None):
    """成功返回格式"""
    d = base_response(HttpResponse.SUCCESS.code, msg, data)
    return d


def fail(msg='', data=None):
    """失败返回格式"""
    return base_response(HttpResponse.FAILED.code, msg, data)


def tableinfo(msg="", total=0, rows=[]):
    return base_response(HttpResponse.SUCCESS.code, msg, None, {"total": total, "rows": rows})


def error(msg="", data=None):
    raise HTTPException(status_code=HttpResponse.NOTSUCCESS.code, detail=msg)


def notAuthenticated(msg=''):
    raise HTTPException(status_code=HttpResponse.UNAUTHORIZED.code, detail="无权限!!!!" if msg == '' else msg)


def accessDenied():
    raise HTTPException(status_code=HttpResponse.FORBIDDEN.code, detail="无权限")


def systemError():
    raise HTTPException(status_code=HttpResponse.SYSTEM_ERROR.code, detail="无权限")
